package com.jsaas.core.qparams;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jsaas.utils.MyUtils;

/**   
* @Title: QueryParamsUtils.java 
* @Package com.jsaas.utils 
* @Description: TODO(对contoller层的查询封装，更方便使用) 
* @author tuozq 
* @date 2017年11月8日 下午2:18:49 
* @version V1.0   
*/
public class QueryParamsUtils {
	
	public static String sortName = "sortName";
	public static String sortOrder = "sortOrder";
	
	/**
	 * 构建分页查询参数
	 * @param ctr
	 * @param sqlkey
	 * @return
	 */
	public static PageQueryParams initPageParams(HttpServletRequest request, String sqlKey){
		PageQueryParams params = new PageQueryParams();
		Kv wheres = getAllParams(request);
		params.setPage(Integer.parseInt(request.getParameter("pageNumber")));
		params.setSize(Integer.parseInt(request.getParameter("pageSize")));
		
		//移除分页所需参数(不属于查询条件)
		wheres.remove("pageSize");
		wheres.remove("pageNumber");
		
		if(StrKit.isBlank(wheres.getStr(sortName))){
			wheres.put(sortName, "id");
		}
		if(StrKit.isBlank(wheres.getStr(sortOrder))){
			wheres.put(sortOrder, "asc");
		}
		
		params.setWheres(wheres);
		
		if(StrKit.notBlank(sqlKey)){
			SqlPara sqlpara = Db.getSqlPara(sqlKey, params.getWheres());
			params.setSqlpara(sqlpara);
		}
		
		return params;
	}
	
	/**
	 * 构建普通查询参数
	 * @param ctr
	 * @param sqlkey
	 * @return
	 */
	public static QueryParams initParams(Controller ctr, String sqlKey){
		QueryParams params = new QueryParams();
		
		Kv wheres = getAllParams(ctr.getRequest());
		params.setWheres(wheres);
		
		if(StrKit.notBlank(sqlKey)){
			SqlPara sqlpara = Db.getSqlPara(sqlKey, params.getWheres());
			params.setSqlpara(sqlpara);
		}
		return params;
	}
	
	/**
	 * 获取请求中的所有参数
	 * @param request
	 * @return
	 */
	public static Kv getAllParams(HttpServletRequest request){
		Kv wheres = Kv.create();
		Enumeration<String> allParameterNames = request.getParameterNames();
		while(allParameterNames.hasMoreElements()){
			String paramsname = allParameterNames.nextElement();
			String paramsvalue = MyUtils.getString(request.getParameter(paramsname)).trim();
			wheres.set(paramsname, paramsvalue);
		}
		return wheres;
	}
	
}
